
#include "task_rtc.h"

void Task_RTC(void * pvParameters)
{
	uint8_t month_day[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
	TickType_t xLastWakeTime;
	const TickType_t xPeriod = pdMS_TO_TICKS( 1000 );
	
	xLastWakeTime = xTaskGetTickCount();
	
	for(;;)
	{
		vTaskDelayUntil( &xLastWakeTime, xPeriod );
		timestamp.second++;
		if(timestamp.second >=60)
		{
			timestamp.second=0;
			timestamp.min++;
			if(timestamp.min>=60)
			{
				timestamp.min=0;
				timestamp.hour++;
				if(timestamp.hour>=24)
				{
					timestamp.hour=0;
					timestamp.day++;
					LeapYear(month_day);
					if(timestamp.day >=month_day[timestamp.month-1])
					{
						timestamp.day=1;
						timestamp.month++;
						if(timestamp.month>12)
						{
							timestamp.month=1;
							timestamp.year++;
						}
					}
				}
			}
		}
	}
}


void LeapYear(uint8_t *month)
{
	if((timestamp.year%100!=0 && timestamp.year%4==0)||(timestamp.year%400))
		month[1] = 28;
	else
		month[1] = 29;
}

uint8_t Zeller_WeekDay(void)
{
	uint8_t y=timestamp.year%100;
	uint8_t c=timestamp.year/100;
	uint8_t m=timestamp.month;
	uint8_t d=timestamp.day;
	
	if(m==1 || m==2)
	{
		y--;
		m +=12;
	}
	int32_t w = y + y / 4 + c / 4 - 2 * c + 13 * (m + 1) / 5 + d - 1;
	while(w<0)
		w+=7;
	return w;
}
